import 'dart:convert';
import 'dart:io';
import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

// #enddocregion platform_imports
import '../../../mvp/base_page.dart';
import '../../../mvp/power_presenter.dart';
import '../../../res/constant.dart';
import '../../../util/common_utils.dart';
import '../../../util/log_utils.dart';
import '../../../widgets/xm_webview/xm_js_msg_call.dart';
import '../../../widgets/xm_webview/xm_web_controller.dart';
import '../../../widgets/xm_webview/xm_webview.dart';

class BaseWebPage extends StatefulWidget {
  @override
  BaseWebState createState() {
    return BaseWebState();
  }
}

class BaseWebState extends State<BaseWebPage>  with
    BasePageMixin<BaseWebPage, PowerPresenter<dynamic>>{
  late XmWebController controller;
  String pageTitle="";
  bool is_need_notice_bar=true;
  var url = "";
  bool isByStepBack = true;

  @override
  void initState() {
    super.initState();
    // String s = "XmjzCapp/" + (SpUtil.getString(Constant.versionName)??"") + (FkUserAgent.webViewUserAgent ?? "");
    // MyLog.e("msg===s=="+s);

    var arguments = Get.arguments;
    url = arguments["url"];
    var argumentIsByStepBack = arguments["isByStepBack"];
    if(argumentIsByStepBack!=null){
      isByStepBack = argumentIsByStepBack;
    }
    MyLog.e("msg---url--url-"+url);
    var argument2 = arguments["is_need_notice_bar"];
    if(arguments["title"]!=null){
      pageTitle = arguments["title"];
    }
    if(argument2!=null){
      is_need_notice_bar = argument2;
    }

    // #docregion webview_controller
    // controller = WebViewController()
    //   // ..setUserAgent(s)
    //   ..setJavaScriptMode(JavaScriptMode.unrestricted) // 设置javascript 是能用的
    //   ..addJavaScriptChannel(
    //     Constant.jsSpaceName,
    //     onMessageReceived: (message) {
    //       ////根据 message 信息跳转
    //       MyLog.e("msg---onMessageReceivedonMessageReceived-message-" + message.message);
    //     },
    //   )
    //   ..setBackgroundColor(const Color(0x00000000))
    //   ..setNavigationDelegate(
    //     NavigationDelegate(
    //       onProgress: (int progress) {
    //         // Update loading bar.
    //       },
    //       onPageStarted: (String url) {
    //         showProgress();
    //       },
    //       onPageFinished: (String url) {
    //         closeProgress();
    //         _getTitle();
    //       },
    //       onWebResourceError: (WebResourceError error) {
    //         MyLog.e("------description----"+error.description);
    //       },
    //       onNavigationRequest: (NavigationRequest request) {
    //         MyLog.e("------1111111--------"+request.url);
    //         //可以做以下功能 url 以 /android 结尾时，跳到对应的原生页面。否则继续原来的请求。
    //         if (request.url.startsWith('https://www.youtube.com/')) {
    //           // 跳到原生页面
    //           return NavigationDecision.prevent;
    //         }
    //         // 继续原来的请求
    //         return NavigationDecision.navigate;
    //       },
    //     ),
    //   )
    //   ..loadRequest(Uri.parse(argument??""));
    // ..loadRequest(Uri.parse(url));
    // #enddocregion webview_controller
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        if(isByStepBack){
          if (await controller.canGoBack()) {
            controller.goBack();
            return false;
          }
        }
        return true;
      },
      child:  Scaffold(
        appBar: is_need_notice_bar?AppBar(title: Center(child: Text("njknjkn"),),):null,
        body: SafeArea(child: XmWebView(
          onPageStarted: (url){
            showProgress();
          },
          onPageFinished: (url){
            closeProgress();
            _getTitle();
          },
          onXmJsMsgCall: (XmJsMsgCall msgCall){
            var decode = json.decode(msgCall.message);
            var name = decode["name"];
            var data = decode["data"];
            switch(name){
              // case "EEBridge_backPage":
              //   Get.back();
              //   break;
            }
            //回调id、方法名称和参数
            //controller.realController.runJavaScript("window.callBackHandle('100000')");
          },
          controllerSettingBack: (value) {
            controller = value;
            if (!TextUtil.isEmpty(url)) {
              controller.loadRequest(
                  Uri.parse(url));
            }
          },
        ),),
      ),);
  }

  // 获取当前加载页面的 title
  _getTitle() async {
    if(pageTitle.isEmpty){
      String? title = await controller.realController.getTitle();
      MyLog.e("msg--title-title---"+title.toString());
      setState(() {
        pageTitle = title??"";
      });
    }
  }

  @override
  PowerPresenter createPresenter() {
    final PowerPresenter<dynamic> powerPresenter =
    PowerPresenter<dynamic>(this);
    return powerPresenter;
  }
}
